import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { useChatStore } from '@/stores/chat'

class WebSocketService {
    private ws: WebSocket | null = null
    private reconnectAttempts = 0
    private maxReconnectAttempts = 5
    private reconnectInterval = 3000
    private heartbeatInterval: number | null = null
    private isConnecting = false

    connect() {
        if (this.ws?.readyState === WebSocket.OPEN || this.isConnecting) {
            return
        }

        this.isConnecting = true
        const authStore = useAuthStore()

        if (!authStore.token) {
            console.warn('No token available for WebSocket connection')
            this.isConnecting = false
            return
        }

        try {
            // 构建WebSocket URL，连接到后端私聊WebSocket服务
            const wsUrl = `ws://123.207.65.217:8080/api/v1/ws/private-chat?token=${authStore.token}`

            this.ws = new WebSocket(wsUrl)

            this.ws.onopen = this.onOpen.bind(this)
            this.ws.onmessage = this.onMessage.bind(this)
            this.ws.onclose = this.onClose.bind(this)
            this.ws.onerror = this.onError.bind(this)

        } catch (error) {
            console.error('WebSocket connection error:', error)
            this.isConnecting = false
        }
    }

    private onOpen() {
        console.log('WebSocket connected')
        this.isConnecting = false
        this.reconnectAttempts = 0

        const chatStore = useChatStore()
        chatStore.isConnected = true

        // 开始心跳
        this.startHeartbeat()

        // 发送连接成功消息
        ElMessage.success('聊天服务已连接')
    }

    private onMessage(event: MessageEvent) {
        try {
            const data = JSON.parse(event.data)
            this.handleMessage(data)
        } catch (error) {
            console.error('Failed to parse WebSocket message:', error)
        }
    }

    private handleMessage(data: any) {
        const chatStore = useChatStore()

        switch (data.type) {
            case 'message':
            case 'new_private_message':
                // 收到新消息
                chatStore.addMessage(data.message || data)
                break

            case 'message_sent':
                // 消息发送确认
                console.log('消息发送确认:', data)
                break

            case 'connected':
                // 连接成功
                console.log('WebSocket连接成功:', data)
                break

            case 'user_online':
                // 用户上线
                this.updateUserOnlineStatus(data.user_id, true)
                break

            case 'user_offline':
                // 用户下线
                this.updateUserOnlineStatus(data.user_id, false)
                break

            case 'typing':
                // 正在输入状态
                this.handleTypingStatus(data)
                break

            case 'pong':
                // 心跳响应
                break

            case 'error':
                // 错误消息
                console.error('WebSocket错误:', data.message)
                break

            default:
                console.log('Unknown message type:', data.type)
        }
    }

    private updateUserOnlineStatus(userId: number, isOnline: boolean) {
        const chatStore = useChatStore()

        // 更新在线用户列表
        const userIndex = chatStore.onlineUsers.findIndex(user => user.id === userId)
        if (userIndex !== -1) {
            chatStore.onlineUsers[userIndex].online = isOnline
        }

        // 更新当前聊天用户的在线状态
        if (chatStore.currentChatUser?.id === userId) {
            chatStore.currentChatUser.online = isOnline
        }

        // 更新对话列表中的用户在线状态
        const conversation = chatStore.conversations.find(conv => conv.other_user_id === userId)
        if (conversation && conversation.other_user) {
            conversation.other_user.online = isOnline
        }
    }

    private handleTypingStatus(data: any) {
        // 处理正在输入状态，可以在这里添加UI提示
        console.log('User typing:', data)
    }

    private onClose(event: CloseEvent) {
        console.log('WebSocket disconnected:', event.code, event.reason)
        this.isConnecting = false

        const chatStore = useChatStore()
        chatStore.isConnected = false

        this.stopHeartbeat()

        // 如果不是主动关闭，尝试重连
        if (event.code !== 1000 && this.reconnectAttempts < this.maxReconnectAttempts) {
            this.scheduleReconnect()
        }
    }

    private onError(error: Event) {
        console.error('WebSocket error:', error)
        this.isConnecting = false

        const chatStore = useChatStore()
        chatStore.isConnected = false

        ElMessage.error('聊天服务连接失败')
    }

    private scheduleReconnect() {
        this.reconnectAttempts++
        console.log(`Attempting to reconnect (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)

        setTimeout(() => {
            this.connect()
        }, this.reconnectInterval)
    }

    private startHeartbeat() {
        this.heartbeatInterval = window.setInterval(() => {
            if (this.ws?.readyState === WebSocket.OPEN) {
                this.send({ type: 'ping' })
            }
        }, 30000) // 每30秒发送一次心跳
    }

    private stopHeartbeat() {
        if (this.heartbeatInterval) {
            clearInterval(this.heartbeatInterval)
            this.heartbeatInterval = null
        }
    }

    send(data: any) {
        if (this.ws?.readyState === WebSocket.OPEN) {
            this.ws.send(JSON.stringify(data))
        } else {
            console.warn('WebSocket is not connected')
        }
    }

    sendMessage(receiverId: number, content: string, messageType = 'text') {
        this.send({
            type: 'private_message',
            data: {
                data: {
                    receiver_id: receiverId,
                    content,
                    type: messageType
                }
            }
        })
    }

    sendTyping(receiverId: number, isTyping: boolean) {
        this.send({
            type: 'typing',
            receiver_id: receiverId,
            is_typing: isTyping
        })
    }

    disconnect() {
        this.stopHeartbeat()

        if (this.ws) {
            this.ws.close(1000, 'User disconnected')
            this.ws = null
        }

        const chatStore = useChatStore()
        chatStore.isConnected = false
    }

    getConnectionState() {
        if (!this.ws) return 'disconnected'

        switch (this.ws.readyState) {
            case WebSocket.CONNECTING:
                return 'connecting'
            case WebSocket.OPEN:
                return 'connected'
            case WebSocket.CLOSING:
                return 'closing'
            case WebSocket.CLOSED:
                return 'disconnected'
            default:
                return 'unknown'
        }
    }
}

// 创建单例实例
export const wsService = new WebSocketService()

// 导出类型
export interface WebSocketMessage {
    type: 'message' | 'user_online' | 'user_offline' | 'typing' | 'ping' | 'pong'
    message?: any
    user_id?: number
    receiver_id?: number
    content?: string
    message_type?: string
    is_typing?: boolean
}


